/*
						  qpdf

	Copyright (C) 2015 Arthur Benilov,
	arthur.benilov@gmail.com
	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.
	This software is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
	Lesser General Public License for more details.
*/

#pragma once

#include <QWebEngineView>
#include <QPointer>
#include <QSemaphore>
#include <QJsonObject>
#include <QJsonValue>

class BridgeObject;

class PdfJsBridge : public QWebEngineView
{
	Q_OBJECT
		friend class BridgeObject;
public:
	explicit PdfJsBridge(QWidget* pParent = nullptr);
	~PdfJsBridge();
	void invokeJavaScript(const QString& script);
	QVariant invokeJavaScriptAndWaitForResult(const QString& script);
	QStringList fetchPdfDocumentDestinations();
	void setToolbarVisible(bool visible);
	QList<QJsonObject> getChapterList();
	void gotoChapter(const QString& strHref);
	int GetCurrentPage();
	void close();

signals:
	void initialized();
	void pdfDocumentloaded();
	void pageNumberChanged(int nPage);
	void pageCountChanged(int nPageCountChanged);
	void pageScaleChanged(double fScale);
	void chapterListLoaded(QList<QJsonObject>& list);
	void findStateChanged(int nState);

protected:
	void contextMenuEvent(QContextMenuEvent* pEvent);

private slots:

	void onLoadFinished(bool ok);

private:
	void jsInitialized();
	void jsReportDestinations(const QStringList& destinations);
	void jsChapterList(const QJsonValue& list);
	void jsChapterListLoaded(const QJsonValue& list);
	void jsCurrentPage(int nPage);
	void jsPageCount(int nPage);
	void jsPageScale(double fScale);
	void jsLoaded();
	void jsClosed();
	void jsFindState(int nState);

	void establishWebChannel();

	QWebChannel* m_pWebChannel;
	QSemaphore m_pdfDestinationsSema;
	QList<QJsonObject> m_pdfChapterList;
	int m_nCurrentPage;
	int m_nPageCount;
	double m_fPageScale;

	QStringList m_pdfDocumentDestinations;

	QSemaphore m_pdfCloseSema;

	BridgeObject* m_pBridgeObject;
};